<template>
  <a-space>
    <a-input v-model:value="packageString" readonly />
    <a-button type="primary" size="small" @click="show">设置</a-button>
  </a-space>

  <a-modal
    v-model:visible="visible"
    title="新增包装单位及规格"
    destroy-on-close
    :mask-closable="false"
    :keyboard="false"
    @ok="submit"
  >
    <a-card>
      <a-form ref="formRef" name="form" :model="form">
        <div v-for="(item, index) in form.packageList" :key="index">
          <a-space>
            <a-form-item
              :name="['packageList', index, 'quantity']"
              :rules="{
                required: true,
                validator: (_rule, value) => {
                  return validateValue(_rule, value, index)
                },
                trigger: 'blur'
              }"
            >
              <a-space>
                <template v-if="index !== 0">=</template>
                <template v-if="index === 0">1</template>
                <template v-else>
                  <a-input-number v-model:value="item.quantity" :precision="0" :min="1" :max="99999"></a-input-number>
                </template>
              </a-space>
            </a-form-item>
            <a-form-item
              :name="['packageList', index, 'specId']"
              :rules="{ required: true, validator: validateUnit, trigger: 'change' }"
            >
              <DictFormItem
                v-model:value="item.specId"
                v-model:name="item.specName"
                value-key="dictDataId"
                placeholder="请选择"
                app-code="Pharmacy"
                flag="DRUG_SPEC"
                :is-http="true"
                @change="changeHandler"
              />
            </a-form-item>
            <template v-if="index !== 0">
              <Icon size="18" class="-mt-6">
                <delete-outlined style="color: #eb4646" @click="deleteItem(index)" />
              </Icon>
            </template>
          </a-space>
        </div>
        <a-button type="link" @click="addItem">新增层级</a-button>
      </a-form>
    </a-card>
  </a-modal>
</template>
<script setup lang="ts">
import { ref, toRefs, withDefaults } from 'vue'
import { DeleteOutlined } from '@vicons/antd'
import { cloneDeep } from 'lodash-es'

const emits = defineEmits(['change', 'update:packageString', 'update:packageList'])

const props = withDefaults(
  defineProps<{
    packageString: string
    packageList: any[]
  }>(),
  { packageString: '', packageList: () => [{ quantity: 1, specId: undefined, specName: undefined }] }
)

const { packageString, packageList } = toRefs(props)

const visible = ref(false)
const form = ref<any>({
  packageList: cloneDeep(packageList.value)
})

const show = () => {
  form.value.packageList = cloneDeep(packageList.value)
  visible.value = true
}

const changeHandler = () => {
  formRef.value.validate()
}

const validateValue = (_rule, value, index) => {
  if (!value) {
    return Promise.reject('请输入包装数量')
  } else if (index > 0) {
    const lastValue = form.value.packageList[index - 1].quantity
    const currValue = form.value.packageList[index].quantity
    if (currValue % lastValue !== 0) {
      return Promise.reject('输入的包装规格不正确')
    }
  }
  return Promise.resolve()
}

const validateUnit = (_rule, value) => {
  if (!value) {
    return Promise.reject('请选择包装单位')
  }
  const arr = form.value.packageList.filter((el) => el.specId === value)
  if (arr.length > 1) {
    return Promise.reject('包装单位不能重复')
  }

  return Promise.resolve()
}

const deleteItem = (index) => {
  form.value.packageList.splice(index, 1)
  formRef.value.validate()
}
const addItem = () => {
  form.value.packageList.push({
    quantity: undefined,
    specId: undefined,
    specName: undefined
  })
}

const formRef = ref()
const submit = () => {
  formRef.value.validate().then((valid) => {
    if (valid) {
      const str = form.value.packageList.reduce((prev, cur, index) => {
        const str = index === 0 ? prev + cur.quantity + cur.specName : prev + '=' + cur.quantity + cur.specName
        return str
      }, '')
      emits('update:packageList', cloneDeep(form.value.packageList))
      emits('update:packageString', str)
      emits('change', { packageSpecName: str, packageSpec: cloneDeep(form.value.packageList) })
      visible.value = false
    }
  })
}
</script>
